package org.simplecrm.controllers.customers;

import org.simplecrm.controllers.customers.propertyeditors.RegionPropertyEditor;
import org.simplecrm.domain.customer.Customer;
import org.simplecrm.domain.event.Event;
import org.simplecrm.domain.event.eventtype.EventType;
import org.simplecrm.domain.region.Region;
import org.simplecrm.domain.user.User;
import org.simplecrm.service.customer.CustomerService;
import org.simplecrm.service.event.eventtype.EventTypeService;
import org.simplecrm.service.region.RegionService;
import org.simplecrm.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.sql.SQLException;
import java.util.List;

import static org.simplecrm.controllers.CrmUrls.*;

/**
 * Created by Oleksandr_Terekh on 9/12/2014.
 */
@Controller
@RequestMapping("/crm/customers")
@SessionAttributes(value = {"regions", "eventTypes", "supportList"})
public class CustomerController {

    private static final int PAGE_SIZE = 3;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private EventTypeService eventTypeService;

    @Autowired
    private UserService userService;

    @ModelAttribute("customer")
    public Customer createNewCustomer() {
        return new Customer();
    }

    @ModelAttribute("regions")
    public List<Region> getRegionList() {
        return regionService.getAllRegions();
    }

    @ModelAttribute("event")
    public Event createNewEvent() {
        return new Event();
    }

    @ModelAttribute("eventTypes")
    public List<EventType> getEventTypeList() {
        return eventTypeService.getAllEventTypes();
    }

    @ModelAttribute("supportList")
    public List<User> getSupportList() {
        return userService.getAllSupports();
    }

    @InitBinder
    public void initBinderAll(WebDataBinder binder) {
        binder.registerCustomEditor(Region.class, new RegionPropertyEditor());
    }

    @RequestMapping("/{pageNum}")
    public ModelAndView viewCustomers(@PathVariable("pageNum") Integer pageNum) {

        ModelAndView modelAndView = new ModelAndView();

        long customersCount = customerService.getCustomersCount();
        int totalPages = (int) Math.ceil((double) customersCount / PAGE_SIZE);

        if (pageNum < 1 || pageNum > totalPages) {
            modelAndView.setViewName(URL_403_PAGE);
            modelAndView.getModelMap().addAttribute("error", "There is no such page!");
            return modelAndView;
        }

        List<Customer> customersPage = customerService.getCustomersPage(pageNum, PAGE_SIZE);

        modelAndView.setViewName(URL_CUSTOMERS_PAGE);
        modelAndView.getModelMap().addAttribute("custList", customersPage);
        modelAndView.getModelMap().addAttribute("lastPage", pageNum * PAGE_SIZE >= customersCount);
        modelAndView.getModelMap().addAttribute("currentPage", pageNum);
        modelAndView.getModelMap().addAttribute("totalPages", totalPages);
        return modelAndView;
    }

    @RequestMapping("/new")
    public String addCustomer(@Valid @ModelAttribute("customer") Customer customer,
                              final BindingResult bindingResult,
                              final RedirectAttributes redirectAttributes) throws SQLException {

        if (bindingResult.hasErrors()) {

            redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.customer", bindingResult);
            redirectAttributes.addFlashAttribute("customer", customer);
        } else {

            customerService.addNewCustomer(customer);
            redirectAttributes.addFlashAttribute("done", true);
        }
        return URL_REDIRECT_CUSTOMERS + "/1";
    }

    @RequestMapping("/delete/{customerId}")
    public String deleteCustomer(@PathVariable("customerId") Integer customerId,
                                 RedirectAttributes redirectAttributes) {

        customerService.deleteCustomer(customerId);
        redirectAttributes.addFlashAttribute("done", true);
        return URL_REDIRECT_CUSTOMERS + "/1";
    }

}
